<?php
namespace app\admin\controller;
use think\Db;
use think\Request;

class Stock extends Base
{
	/**
	 * 商品列表
	 * @return [type] [description]
	 */
	function index(){
		$keywords = Request()->get('keywords');
		$sort = Request()->get('lastent_time')?Request()->get('lastent_time'):"lastent_time desc";
        $this->assign('sort',$sort);
        $Query = Db::field('')->table('sdzx_stock')->alias('s')
        ->join('sdzx_goods g','s.goods_id=g.goods_id')
        ->join('sdzx_goods_specval sval','s.specval_id=sval.specval_id')
        ->where('s.stock_num>0')
        ->order($sort);
        if ($keywords) {
            $Query->where("g.goods_name like '%{$keywords}%'");
        }
		
        $list = $Query->paginate('',false,['query'=>Request()->param()]);
		
		foreach($list as $key => $val){
			$val['detail'] = db('stock_detail')->where('specval_id',$val['specval_id'])->whereTime('time', 'between', [date("Y-m-d",strtotime("-7 day")), date("Y-m-d H:i:s",time())])->order('time desc')->select();
			$list->offsetSet($key, $val);
		}

        $data['list'] = $list;
        return $this->fetch('index',$data);
	}

	public function _purchase($v)
	{
		$tmp = Db::connect([],'pg')->name('purchase_goods')->where(['specval_id'=>$v['specval_id'],'status'=>['neq',1],'real_num'=>['gt',0]])->order('create_time asc')->find();
		if (!$tmp) { // 多余的入库
			// $tmp = Db::connect([],'pg')->name('purchase_goods')->where(['specval_id'=>$v['specval_id']])->order('create_time asc')->find();

			$tmp = Db::field('g.goods_name,g.goods_id,sval.specval_id,sval.specval_name,g.brand_name,sum(pg.entstock_num) as entstock_num,sum(pg.num) as num,sum(pg.real_num) as real_num,sval.price as mall_price,g.picture,pg.cur_price')
			->table('sdzx_goods_specval')->alias('sval')
			->join('sdzx_goods g','sval.goods_id=g.goods_id')
			->join('sdzx_purchase_goods pg','sval.specval_id=pg.specval_id and pg.status=0 and pg.real_num>0','left')
			->where("sval.specval_id={$v['specval_id']}")
			->group('sval.specval_id')
			->find();

			$stock_id = Db::connect([],'pg')->name('stock')->where(['specval_id' => $v['specval_id']])->value('stock_id');
			if ($stock_id) { //存在
				//库存
				$re_stock = Db::connect([],'pg')->name('stock')->where(['stock_id'=>$stock_id])->update([
					'depot_id'      => 1,
					'goods_id'      => $tmp['goods_id'],
					'specval_id'    => $v['specval_id'],
					'stock_num'     => ['exp',"stock_num+{$v['num']}"],
					'lastent_time'  => date("Y-m-d H:i:s"),
					'lastent_price' => $tmp['cur_price']?:$v['enter_price'],
				]);
				if (!$re_stock) {
					Db::connect([],'pg')->rollback(); $this->error('入库失败1','');
				}
			}else{
				//库存
				$re_stock = Db::connect([],'pg')->name('stock')->insertGetId([
					'depot_id'      => 1,
					'goods_id'      => $tmp['goods_id'],
					'specval_id'    => $v['specval_id'],
					'stock_num'     => $v['num'],
					'lastent_time'  => date("Y-m-d H:i:s"),
					'lastent_price' => $tmp['cur_price']?:$v['enter_price'],
				]);
				if (!$re_stock) {
					Db::connect([],'pg')->rollback(); $this->error('入库失败2','');
				}
				$stock_id = $re_stock;
			}

			//库存详情
			// -10：退货出库
			// -1  ：配送出库
			// 1  ：采购入库
			// 10：退单入库
			Db::connect([],'pg')->name('stock_detail')->insert([
				'stock_id'     => $stock_id,
				'goods_id'     => $tmp['goods_id'],
				'specval_name' => $tmp['specval_name'],
				'specval_id'   => $tmp['specval_id'],
				'type'         => 1,
				'num'          => $v['num'],
				'price'        => $tmp['cur_price']?:$v['enter_price'],
				'time'         => date("Y-m-d H:i:s"),
				'uid'          => $this->uid,
				'uname'        => $this->user['name'],
				'purchase_id'  => $tmp['purchase_id']?:null
			]);
			return true;
		}

		$tmp_num = $v['num'];
		// $_real_num = $tmp['real_num']?:$tmp['num'];
		$_real_num = $tmp['real_num'];

		if (($_real_num-$tmp['entstock_num']) <= $v['num']) { //说明已经采完
			$tmp_num = $_real_num-$tmp['entstock_num'];
	
			$re_pg = Db::connect([],'pg')->name('purchase_goods')->where(['pg_id'=>$tmp['pg_id']])->fetchSql(false)->update([
				'entstock_num'=>['exp',"entstock_num+{$tmp_num}"],
				'status' => 1
			]);
			if ($tmp_num) {
				# code...
			
				$stock_id = Db::connect([],'pg')->name('stock')->where(['specval_id' => $v['specval_id']])->value('stock_id');

				if ($stock_id) { //存在
					//库存
					$re_stock = Db::connect([],'pg')->name('stock')->where(['stock_id'=>$stock_id])->update([
						'depot_id'      => 1,
						'goods_id'      => $tmp['goods_id'],
						'specval_id'    => $v['specval_id'],
						'stock_num'     => ['exp',"stock_num+{$tmp_num}"],
						'lastent_time'  => date("Y-m-d H:i:s"),
						'lastent_price' => $tmp['cur_price']?:$v['enter_price'],
					]);
					if (!$re_stock) {
						Db::connect([],'pg')->rollback(); $this->error('入库失败1','');
					}
				}else{
					//库存
					$re_stock = Db::connect([],'pg')->name('stock')->insertGetId([
						'depot_id'      => 1,
						'goods_id'      => $tmp['goods_id'],
						'specval_id'    => $v['specval_id'],
						'stock_num'     => $tmp_num,
						'lastent_time'  => date("Y-m-d H:i:s"),
						'lastent_price' => $tmp['cur_price']?:$v['enter_price'],
					]);
					if (!$re_stock) {
						Db::connect([],'pg')->rollback(); $this->error('入库失败2','');
					}
					$stock_id = $re_stock;
				}

				//库存详情
				// -10：退货出库
				// -1  ：配送出库
				// 1  ：采购入库
				// 10：退单入库
				Db::connect([],'pg')->name('stock_detail')->insert([
					'stock_id'     => $stock_id,
					'goods_id'     => $tmp['goods_id'],
					'specval_name' => $tmp['specval_name'],
					'specval_id'   => $tmp['specval_id'],
					'type'         => 1,
					'num'          => $tmp_num,
					'price'        => $tmp['cur_price']?:$v['enter_price'],
					'time'         => date("Y-m-d H:i:s"),
					'uid'          => $this->uid,
					'uname'        => $this->user['name'],
					'purchase_id'  => $tmp['purchase_id']
				]);
			}
			if ($v['num']-$tmp_num) {
				self::_purchase([
					'specval_id' => $v['specval_id'],
					'num' => ($v['num']-$tmp_num),
					'enter_price' => $v['specval_id'],
				]);
			}
		}else{
			$re_pg = Db::connect([],'pg')->name('purchase_goods')->where(['pg_id'=>$tmp['pg_id']])->update([
				'entstock_num'=>['exp',"entstock_num+{$tmp_num}"]
			]);

			$stock_id = Db::connect([],'pg')->name('stock')->where(['specval_id' => $v['specval_id']])->value('stock_id');

			if ($stock_id) { //存在
				//库存
				$re_stock = Db::connect([],'pg')->name('stock')->where(['stock_id'=>$stock_id])->update([
					'depot_id'      => 1,
					'goods_id'      => $tmp['goods_id'],
					'specval_id'    => $v['specval_id'],
					'stock_num'     => ['exp',"stock_num+{$tmp_num}"],
					'lastent_time'  => date("Y-m-d H:i:s"),
					'lastent_price' => $tmp['cur_price']?:$v['enter_price'],
				]);
				if (!$re_stock) {
					Db::connect([],'pg')->rollback(); $this->error('入库失败3','');
				}
			}else{
				//库存
				$re_stock = Db::connect([],'pg')->name('stock')->insertGetId([
					'depot_id'      => 1,
					'goods_id'      => $tmp['goods_id'],
					'specval_id'    => $v['specval_id'],
					'stock_num'     => $tmp_num,
					'lastent_time'  => date("Y-m-d H:i:s"),
					'lastent_price' => $tmp['cur_price']?:$v['enter_price'],
				]);
				if (!$re_stock) {
					Db::connect([],'pg')->rollback(); $this->error('入库失败4','');
				}
				$stock_id = $re_stock;
			}

			//库存详情
			// -10：退货出库
			// -1  ：配送出库
			// 1  ：采购入库
			// 10：退单入库
			Db::connect([],'pg')->name('stock_detail')->insert([
				'stock_id'     => $stock_id,
				'goods_id'     => $tmp['goods_id'],
				'specval_name' => $tmp['specval_name'],
				'specval_id'   => $tmp['specval_id'],
				'type'         => 1,
				'num'          => $tmp_num,
				'price'        => $tmp['cur_price']?:$v['enter_price'],
				'time'         => date("Y-m-d H:i:s"),
				'uid'          => $this->uid,
				'uname'        => $this->user['name'],
				'purchase_id'  => $tmp['purchase_id']
			]);
		}
	}

	/**
	 * 入库操作
	 * @return [type] [description]
	 */
	function entStock(){
		if (Request()->isPost()) {
			$param = Request()->param();
			$data = $param['data'];

			$time = date('Y-m-d H:i:s');

			Db::connect([],'pg')->startTrans();
			foreach ($data as $k => $v) {
				self::_purchase($v);
			}
			Db::connect([],'pg')->commit();

			Db::execute('update `sdzx_purchase` set `status`=1 where purchase_id in (SELECT a.purchase_id FROM (select p.purchase_id from `sdzx_purchase` p inner JOIN `sdzx_purchase_goods` pg on p.purchase_id=pg.purchase_id  where  p.`status`=0 GROUP BY p.purchase_id HAVING min(pg.`status`)=1) a)');
			$this->success('入库成功',url('entStock'));

			// $purchase_id=0;
			// Db::connect([],'pg')->startTrans();
			// foreach ($data as $k => $v) {
			// 	if (!$purchase_id) {
			// 		$purchase_id=$v['purchase_id'];
			// 	}
			// 	$old = Db::connect([],'pg')->name('purchase_goods')->where(['purchase_id'=>$v['purchase_id'],'specval_id'=>$v['specval_id']])->find();
			// 	if (empty($old)) {continue;}
	
			// 	$w = "purchase_id={$v['purchase_id']} and specval_id={$v['specval_id']}";

			// 	$re_pg = Db::connect([],'pg')->name('purchase_goods')->where($w)->setInc('entstock_num',$v['num']);
			// 	if (!$re_pg) {
			// 		Db::connect([],'pg')->rollback(); $this->error('入库失败',url('entOrder'));
			// 	}

			// 	if ($v['real_num'] != $old['real_num']) {
			// 		Db::connect([],'pg')->name('purchase_goods')->where(['purchase_id'=>$v['purchase_id'],'specval_id'=>$v['specval_id']])->update(['real_num'=>$v['real_num']]);
			// 	}
				
			// 	//不管仓库了
			// 	$stock_id = Db::connect([],'pg')->name('stock')->where([
			// 		'goods_id'      => $old['goods_id'],
			// 		'specval_id'    => $v['specval_id'],
			// 	])->value('stock_id');

			// 	if ($stock_id) { //存在
			// 		//库存
			// 		$re_stock = Db::connect([],'pg')->name('stock')->where(['stock_id'=>$stock_id])->update([
			// 			'depot_id'      => 1,
			// 			'goods_id'      => $old['goods_id'],
			// 			'specval_id'    => $v['specval_id'],
			// 			'stock_num'     => ['exp',"stock_num+{$v['num']}"],
			// 			'lastent_time'  => $time,
			// 			'lastent_price' => $old['cur_price']?:$v['enter_price'],
			// 		]);
			// 		if (!$re_stock) {
			// 			Db::connect([],'pg')->rollback(); $this->error('入库失败',url('entOrder'));
			// 		}
			// 	}else{
			// 		//库存
			// 		$re_stock = Db::connect([],'pg')->name('stock')->insertGetId([
			// 			'depot_id'      => 1,
			// 			'goods_id'      => $old['goods_id'],
			// 			'specval_id'    => $v['specval_id'],
			// 			'stock_num'     => $v['num'],
			// 			'lastent_time'  => $time,
			// 			'lastent_price' => $old['cur_price']?:$v['enter_price'],
			// 		]);
			// 		if (!$re_stock) {
			// 			Db::connect([],'pg')->rollback(); $this->error('入库失败',url('entOrder'));
			// 		}
			// 		$stock_id = $re_stock;
			// 	}

			// 	//库存详情
			// 	// -10：退货出库
			// 	// -1  ：配送出库
			// 	// 1  ：采购入库
			// 	// 10：退单入库
			// 	Db::connect([],'pg')->name('stock_detail')->insert([
			// 		'stock_id'     => $stock_id,
			// 		'goods_id'     => $old['goods_id'],
			// 		'specval_name' => $old['specval_name'],
			// 		'specval_id'   => $old['specval_id'],
			// 		'type'         => 1,
			// 		'num'          => $v['num'],
			// 		'price'        => $old['cur_price']?:$v['enter_price'],
			// 		'time'         => $time,
			// 		'uid'          => $this->uid,
			// 		'uname'        => $this->user['name'],
			// 		'purchase_id'  => $v['purchase_id']
			// 	]);
			// 	$sign = 0;
			// 	//如果该单所有商品入库完成则修改采购单状态
			// 	$purchase = Db::connect([],'pg')->name('purchase_goods')->where("purchase_id={$purchase_id}")->select();
			// 	foreach ($purchase as $kk => $vv) {
			// 		$sign = true;
			// 		if ($vv['real_num']>0) { //如果有实采数量则不能大于实采数量
			// 			if ($vv['entstock_num'] < $vv['real_num']) {
			// 				$sign = false; break;
			// 			}
			// 		}else{
			// 			if ($vv['entstock_num'] < $vv['num']) {
			// 				$sign = false; break;
			// 			}
			// 		}
			// 	}
			// 	if ($sign===true) {
			// 		$re_p = Db::connect([],'pg')->name('purchase')->where("purchase_id={$purchase_id}")->update(['status'=>1]);
			// 		if ($re_p===false) {
			// 			Db::connect([],'pg')->rollback(); $this->error('入库失败',url('entOrder'));
			// 		}
			// 	}
			// }
			// Db::connect([],'pg')->commit();
			// $this->success('入库成功',url('entOrder'));

		}else{
			$goods = Db::field('pg.goods_name,pg.picture,pg.goods_id,pg.specval_id,pg.specval_name,pg.price,pg.cur_price,pg.brand_name,sum(pg.entstock_num) as entstock_num,sum(pg.num) as num,sum(pg.real_num) as real_num,sval.price as mall_price')
			->table('sdzx_purchase_goods')->alias('pg')
			->join('sdzx_goods_specval sval','pg.specval_id=sval.specval_id')
			->where(['pg.status'=>0])
			->group('pg.specval_id')
			->select();

			return $this->fetch('',['list'=>$goods]);

			// $purchase_id = Request()->param('purchase_id');
	  //       $purchase = Db::name('purchase')->where(['purchase_id'=>$purchase_id,'status'=>0])->find();


	        // !$purchase && $this->error('参数错误');

	        // //订单商品
	        // $goods = Db::field('pg.*,sval.price as mall_price')->table('sdzx_purchase_goods')->alias('pg')
         //        ->join('sdzx_goods_specval sval','pg.specval_id=sval.specval_id')
         //        ->where(['purchase_id'=>['in',$purchase_id]])->select();
	        // $data['list'] = $goods;
	        // $data['purchase'] = $purchase;
	        // return $this->fetch('entstock',$data);
		}
		
	}

	public function scanadd()
	{
		$param = request()->param();
		$specval_id = isset($param['specval_id'])?$param['specval_id']:0;
		$info = Db::field('g.goods_name,g.goods_id,sval.specval_id,sval.specval_name,g.brand_name,sum(pg.entstock_num) as entstock_num,sum(pg.num) as num,sum(pg.real_num) as real_num,sval.price as mall_price,g.picture,pg.cur_price')
			->table('sdzx_goods_specval')->alias('sval')
			->join('sdzx_goods g','sval.goods_id=g.goods_id')
			->join('sdzx_purchase_goods pg','sval.specval_id=pg.specval_id and pg.status=0','left')
			->where("sval.specval_id={$specval_id}")
			->group('sval.specval_id')
			->find();
		if ($info) {
			empty($info['num']) && $info['num']=0;
			empty($info['real_num']) && $info['real_num']=0;
			empty($info['entstock_num']) && $info['entstock_num']=0;
			empty($info['cur_price']) && $info['cur_price']=0;
			$this->success('success','',$info);
		}else{
			$this->error('无该规格商品');
		}

	}

	/**
	 * 待入库单
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function entOrder()
	{
		$keywords = Request()->get('keywords');
        $sort = Request()->get('create_time')?Request()->get('create_time'):"create_time desc";
        $this->assign('sort',$sort);
        $Query = Db::name('purchase')->where('status=0')->order($sort);

        if ($keywords) {
            $Query->where("employee_name like '%{$keywords}%' or create_name like '%{$keywords}%' ");
        }
        $list = $Query->order('purchase_id asc')->paginate('',false,['query'=>Request()->param()]);

        $orders = [];
        foreach ($list->toArray()['data'] as $key => $value) {
        	$orders[$value['purchase_id']] = $value;
        }
        
        //一口气查出商品
        $purchase_id = array_column($orders, 'purchase_id');
        $purchase_id=$purchase_id?:0;
        $goods = Db::field()->table('sdzx_purchase_goods')->alias('pg')->where(['purchase_id'=>['in',$purchase_id]])->select();

        //商品归类
        foreach ($goods as $k => $v) {
        	$orders[$v['purchase_id']]['list'][]=$v;
        }
        return $this->fetch('entorder',['list'=>$orders,'page'=>$list->render()]);
	}

	/**
	 * 快捷编辑
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function quickedit()
	{
		$param = request()->param();
		!$param['stock_id'] && $this->error('参数错误');
		!$param['field'] && $this->error('参数错误');

		$data[$param['field']] = $param['value'];
		$re = Db::name('stock')->where(['stock_id'=>$param['stock_id']])->update($data);
		if ($re) {
			$this->success('编辑成功','');
		}else{
			$this->error('参数错误');
		}
	}

	/**
	 * 手动入库
	 * @return [type] [description]
	 */
	public function entstockByhand()
	{
		$keywords = Request()->get('keywords');
		$cate_id = Request()->get('cate_id');

		$category = Db::name('goods_category')->where(['cate_status'=>1])->select();
		$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');

		$query = Db::table('sdzx_goods')->field('g.*,b.brand_name,s.supplier_name,sval.*,stk.stock_num')->alias('g')
		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
		->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
		->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
		->join('sdzx_stock stk','sval.specval_id=stk.specval_id','left')
		->order('g.goods_id desc')
		->group('sval.specval_id');
		if ($keywords) {
			$query->where(" g.goods_name like '%{$keywords}%' or b.brand_name like '%{$keywords}%' or s.supplier_name like '%{$keywords}%' ");
		}
		if ($cate_id) {
			$w_cateId = implode(',',array_column($cat->getChildren($cate_id,$category),'cate_id'));
			$query->where("g.category_id in({$w_cateId})");
		}
		$list=$query->order('g.goods_id desc')->paginate('',false,['query'=>Request()->param()]);
		

		return $this->fetch('',['list'=>$list,'catelist'=>$cat->getList(0,$category)]);
	}

	/**
	 * [FunctionName description]
	 * @param string $value [description]
	 */
	public function actEsbh()
	{
		$param = request()->param();
		if (request()->isPost()) {
			if ($param['stock_num']<=0) { $this->error('入库数量必须大于0');}
			Db::startTrans();
			$stock = Db::name('stock')->where(['specval_id'=>$param['specval_id']])->find();
			$stock_id = 0;
			if ($stock) {
				$re_stock = Db::name('stock')->where(['stock_id'=>$stock['stock_id']])->setInc('stock_num',$param['stock_num']);
				$stock_id = $stock['stock_id'];
				if ($re_stock===false) {Db::rollback(); $this->error('操作失败');}
			}else{
				$stock_id = Db::name('stock')->insertGetId([
					'depot_id'      => 1,
					'goods_id'      => $param['goods_id'],
					'specval_id'    => $param['specval_id'],
					'stock_num'     => $param['stock_num'],
					'lastent_time'  => date('Y-m-d H:i:s'),
					'lastent_price' => $param['lastent_price']
				]);
				if (!$stock_id) {Db::rollback(); $this->error('操作失败');}
			}

			$sd = [
				'stock_id'     => $stock_id,
				'depot_id'     => 1,
				'goods_id'     => $param['goods_id'],
				'specval_name' => $param['specval_name'],
				'specval_id'   => $param['specval_id'],
				'type'         => 2,
				'num'          => $param['stock_num'],
				'price'        => $param['lastent_price'],
				'time'         => date('Y-m-d H:i:s'),
				'uid'          => $this->uid,
				'uname'        => $this->user['name'],
				'remark'       => $param['remark']
			];

			$re_sd = Db::name('stock_detail')->insert($sd);
			if (!$re_sd) {Db::rollback(); $this->error('操作失败');}

			Db::commit();
			$this->success('操作成功');
		}else{
			$info = Db::table('sdzx_goods')->field('g.*,b.brand_name,s.supplier_name,sval.*,stk.stock_num')->alias('g')
				->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
				->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
				->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
				->join('sdzx_stock stk','sval.specval_id=stk.specval_id','left')
				->group('sval.specval_id')
				->where("sval.specval_id={$param['specval_id']}")
				->find();

			return $this->fetch('',['info'=>$info]);
		}
	}

	/**
	 * 库存明细
	 * @return [type] [description]
	 */
	public function stockDetail()
	{
		$list = Db::field('sd.*,g.picture,g.goods_name,gb.brand_name')
		->table('sdzx_stock_detail')->alias('sd')
		->join('sdzx_goods g','sd.goods_id=g.goods_id','left')
		->join('sdzx_goods_brand gb','g.brand_id=gb.brand_id','left')
		->order('time desc')->paginate();
		return $this->fetch('',['list'=>$list]);
	}
}